/// Author:					Joe Audette
/// Created:				2004-10-21
/// Last Modified:		    2011-02-18
/// 
/// The use and distribution terms for this software are covered by the 
/// Common Public License 1.0 (http://opensource.org/licenses/cpl.php)
/// which can be found in the file CPL.TXT at the root of this distribution.
/// By using this software in any fashion, you are agreeing to be bound by 
/// the terms of this license.
///
/// You must not remove this notice, or any other, from this software.
///  2011-02-18 Joe Davis added supprtfor the pager in the jquery cycle sideshow

using System;
using System.Configuration;
using System.Data;
using System.Web.UI.WebControls;
using mojoPortal.Business;
using mojoPortal.Business.WebHelpers;
using mojoPortal.Web.Framework;
using mojoPortal.Web.UI;
using Resources;

namespace mojoPortal.Web.ContentUI
{

    public partial class HtmlModule : SiteModuleControl, IWorkflow
    {
       
        protected string EditContentImage = WebConfigSettings.EditContentImage;
        protected HtmlConfiguration config = new HtmlConfiguration();
        private bool isAdmin = false;
        private HtmlRepository repository = new HtmlRepository();


        #region OnInit

        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);
            this.Load += new EventHandler(Page_Load);
            
        }

        
        #endregion

        protected void Page_Load(object sender, EventArgs e) 
		{
            LoadSettings();
            PopulateControls();
			
        }

        
		private void PopulateControls()
		{
            string htmlBody = String.Empty;
            bool retrieveHtml = true;

            if (EnableWorkflow)
            {
                //use mojo base page to see if user has toggled draft content:
                CmsPage cmsPage = this.Page as CmsPage;
                if (cmsPage != null)
                {
                    if (cmsPage.ViewMode == PageViewMode.WorkInProgress)
                    {
                        //try to get draft content:
                        ContentWorkflow workInProgress = ContentWorkflow.GetWorkInProgress(this.ModuleGuid);
                        if (workInProgress != null)
                        {
                            Title1.WorkflowStatus = workInProgress.Status;
                            htmlBody = workInProgress.ContentText;
                            retrieveHtml = false;
                        }
                    }
                }
            }

            if (retrieveHtml)
            {
                //html not yet retrieved:
                
                HtmlContent html = repository.Fetch(ModuleId);
                if (html != null)
                {
                    htmlBody = html.Body;
                }
            }

            //see if the literal has already been added:
            Literal literalHtml = divContent.FindControl("literalHtml") as Literal;

            if (!String.IsNullOrEmpty(htmlBody))
            {
                if (literalHtml == null)
                {
                    literalHtml = new Literal();
                    literalHtml.ID = "literalHtml";
                    divContent.Controls.Add(literalHtml);
                }
                literalHtml.Text = htmlBody;
            }
            else if (literalHtml != null)
            {
                literalHtml.Text = String.Empty;
            }

            fbLike.Visible = (config.ShowFacebookLikeButton && !RenderInWebPartMode);
            fbLike.ColorScheme = config.FacebookLikeButtonTheme;
            fbLike.ShowFaces = config.FacebookLikeButtonShowFaces;
            fbLike.HeightInPixels = config.FacebookLikeButtonHeight;
            fbLike.WidthInPixels = config.FacebookLikeButtonWidth;

		}


        private void LoadSettings()
        {
            Title1.EditUrl = SiteRoot + "/HtmlEdit.aspx";
            Title1.EditText = Resource.EditImageAltText;
            Title1.ToolTip = Resource.EditImageAltText;
            
            Title1.Visible = !this.RenderInWebPartMode;

            if ((WebUser.IsAdminOrContentAdmin) || (SiteUtils.UserIsSiteEditor()))
            { 
                isAdmin = true;
                Title1.IsAdminEditor = isAdmin;
            }

            if (IsEditable)
            {
                TitleUrl = SiteRoot + "/HtmlEdit.aspx" + "?mid=" + ModuleId.ToInvariantString()
                        + "&pageid=" + currentPage.PageId.ToInvariantString();
            }

            config = new HtmlConfiguration(Settings);

            if (config.InstanceCssClass.Length > 0) { pnlWrapper.CssClass += " " + config.InstanceCssClass; }

            if ((config.IncludeSwfObject)&&(Page is mojoBasePage))
            {
                mojoBasePage p = Page as mojoBasePage;
                if (p != null) { p.ScriptConfig.IncludeSwfObject = true; }
            }
            
            if (this.ModuleConfiguration != null)
            {
                this.Title = this.ModuleConfiguration.ModuleTitle;
                this.Description = this.ModuleConfiguration.FeatureName;
            }

           
            Rating.Enabled = config.EnableContentRatingSetting;
            Rating.AllowFeedback = config.EnableRatingCommentsSetting;
            Rating.ContentGuid = ModuleGuid;
           

            pnlContainer.ModuleId = this.ModuleId;

            if (config.EnableSlideShow)
            {
                divContent.EnableSlideShow = true;
                divContent.Random = config.RandomizeSlides;
                divContent.CleartypeNoBg = !config.UseSlideClearTypeCorrections;
                divContent.SlideContainerClass = config.SlideContainerClass;
                divContent.PauseOnHover = config.PauseSlideOnHover;
                divContent.TransitionEffect = config.SlideTransitions;
                divContent.TransitionInterval = config.SlideDuration;
                divContent.Speed = config.TransitionSpeed;

                if (config.SlideContainerHeight > 0) { divContent.ContainerHeight = config.SlideContainerHeight.ToInvariantString() + "px"; }

                if (config.EnableSlideShowPager)
                {
                    divContent.Pager = "cyclenav";
                    if (config.SlideShowPagerBefore) { divContent.PagerBefore = true; }
                }

            }

            

        }

        void html_ContentChanged(object sender, ContentChangedEventArgs e)
        {
            IndexBuilderProvider indexBuilder = IndexBuilderManager.Providers["HtmlContentIndexBuilderProvider"];
            if (indexBuilder != null)
            {
                indexBuilder.ContentChangedHandler(sender, e);
            }
        }

        #region IWorkflow Members

        public void SubmitForApproval()
        {
            if (currentPage == null) { return; }

            SiteUser currentUser = SiteUtils.GetCurrentSiteUser();
            if (currentUser == null) { return; }

            ContentWorkflow workInProgress = ContentWorkflow.GetWorkInProgress(ModuleGuid);
            if (workInProgress == null) { return; }

            Module module = new Module(workInProgress.ModuleId);

            workInProgress.Status = ContentWorkflowStatus.AwaitingApproval;
            workInProgress.LastModUserGuid = currentUser.UserGuid;
            workInProgress.LastModUtc = DateTime.UtcNow;
            workInProgress.Save();

            if (!WebConfigSettings.DisableWorkflowNotification)
            {
                string approverRoles = currentPage.EditRoles + module.AuthorizedEditRoles;

                WorkflowHelper.SendApprovalRequestNotification(
                    SiteUtils.GetSmtpSettings(),
                    siteSettings,
                    currentUser,
                    workInProgress,
                    approverRoles,
                    SiteUtils.GetCurrentPageUrl());
            }

            WebUtils.SetupRedirect(this, Request.RawUrl);

            
        }

        public void CancelChanges()
        {
            
            SiteUser currentUser = SiteUtils.GetCurrentSiteUser();
            if (currentUser == null) { return; }

            ContentWorkflow workInProgress = ContentWorkflow.GetWorkInProgress(ModuleGuid);
            if (workInProgress == null) { return; }

            workInProgress.Status = ContentWorkflowStatus.Cancelled;
            workInProgress.LastModUserGuid = currentUser.UserGuid;
            workInProgress.LastModUtc = DateTime.UtcNow;
            workInProgress.Save();

            WebUtils.SetupRedirect(this, Request.RawUrl);

        }

        public void Approve()
        {
            SiteUser currentUser = SiteUtils.GetCurrentSiteUser();
            if (currentUser == null) { return; }

            HtmlContent html = repository.Fetch(ModuleId);
            if (html != null)
            {
                html.ContentChanged += new ContentChangedEventHandler(html_ContentChanged);
                html.ApproveContent(siteSettings.SiteGuid, currentUser.UserGuid);
            }

            WebUtils.SetupRedirect(this, Request.RawUrl);
        }

        #endregion

    }
}
